import api from '@/api';

export default {
  namespace: 'beanRule',

  state: {
    beanRules: {
      list: [],
      pagination: {},
    },
    currentBeanRule: {},
    memberLevels: [],
    products: [],
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(api.beanRule.query, payload);
      if (response.errorCode === 0) {
        yield put({
          type: 'saveRules',
          payload: response,
        });
      }
      return response;
    },
    *fetchCurrent({ payload }, { call, put }) {
      const response = yield call(api.beanRule.queryCurrent, payload);
      if (response.errorCode === 0) {
        yield put({
          type: 'saveCurrent',
          payload: response.data,
        });
      }
      return response;
    },
    *add({ payload }, { call }) {
      return yield call(api.beanRule.create, payload);
    },
    *update({ payload }, { call }) {
      return yield call(api.beanRule.update, payload);
    },
    *delete({ payload }, { call }) {
      return yield call(api.beanRule.delete, payload);
    },
    *handleEnable({ payload }, { call }) {
      return yield call(api.beanRule.enable, payload);
    },
    *handleDisable({ payload }, { call }) {
      return yield call(api.beanRule.disable, payload);
    },
    *fetchMemberLevel({ payload }, { call, put }) {
      const response = yield call(api.beanRule.queryMemberLevel, payload);
      if (response.errorCode === 0) {
        yield put({
          type: 'saveMemberLevel',
          payload: response.data,
        });
      }
      return response;
    },
    *fetchProducts({ payload }, { call, put }) {
      const response = yield call(api.beanRule.queryProducts, payload);

      if (response.errorCode === 0) {
        yield put({
          type: 'saveProducts',
          payload: response.data,
        });
      }
      return response;
    },
  },

  reducers: {
    saveRules(state, action) {
      const { data, pagination } = action.payload;
      return {
        ...state,
        beanRules: {
          list: data,
          pagination,
        },
      };
    },
    saveCurrent(state, { payload }) {
      return {
        ...state,
        currentBeanRule: payload,
      };
    },
    clearCurrent(state) {
      return {
        ...state,
        currentBeanRule: {},
      };
    },
    saveMemberLevel(state, { payload }) {
      return {
        ...state,
        memberLevels: payload,
      };
    },
    clearMemberLevel(state) {
      return {
        ...state,
        memberLevels: [],
      };
    },
    saveProducts(state, { payload }) {
      return {
        ...state,
        products: payload,
      };
    },
    clearProducts(state) {
      return {
        ...state,
        products: [],
      };
    },
  },
};
